package com.lcz.manage.forkjoin;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

/**
 * ForkJoin test
 *
 * @author lucz@yunrong.cn
 * @version V3.0
 * @date 2021/11/19 14:35
 */
@Slf4j
public class ForkJoinTest2 {

    @Test
    public void test() {
        List<String> tableNames = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11");
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        try {
            forkJoinPool.invoke(new AutoPartitionTask(tableNames));
            forkJoinPool.awaitTermination(5, TimeUnit.SECONDS);
        } catch (Exception ex) {
            log.error("==========error===========", ex);
        } finally {
            forkJoinPool.shutdown();
        }
    }

    public static class AutoPartitionTask extends RecursiveAction {

        private static final long serialVersionUID = 5164916698423764435L;

        private final List<String> tableNames;

        public AutoPartitionTask(List<String> tableNames) {
            this.tableNames = tableNames;
        }

        @Override
        protected void compute() {
            if (tableNames.size() == 1) {
                //创建分区
                doPartitions(tableNames.get(0));
            } else {
                //拆分job
                doSeparateTask();
            }
        }

        private void doPartitions(String tableName) {
            if ("6".equals(tableName)) {
                log.error("error.tableName:{}", tableName);
                throw new NullPointerException("error.tableName:" + tableName);
            }
            log.info("do biz.tableName:{}", tableName);
        }

        private void doSeparateTask() {
            int size = tableNames.size();
            int middle = size / 2;
            List<String> left = tableNames.subList(0, middle);
            List<String> right = tableNames.subList(middle, tableNames.size());
            AutoPartitionTask leftTask = new AutoPartitionTask(left);
            leftTask.fork();
            AutoPartitionTask rightTask = new AutoPartitionTask(right);
            rightTask.fork();
        }
    }

}
